<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="开始日期" prop="beginDate">
        <el-date-picker v-model="queryParams.beginDate" type="date" placeholder="请选择开始日期" value-format="YYYYMMDD"
          style="width: 180px" />
      </el-form-item>
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker v-model="queryParams.endDate" type="date" placeholder="请选择结束日期" value-format="YYYYMMDD"
          style="width: 180px" />
      </el-form-item>
      <el-form-item label="交易状态" prop="isOpen">
        <el-select v-model="queryParams.isOpen" placeholder="请选择交易状态" style="width: 120px" clearable>
          <el-option label="交易日" value="1" />
          <el-option label="休市日" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">查询</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Plus" @click="handleAdd" v-hasPermi="['kylin:tradeCal:add']">
          新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Edit" :disabled="single" @click="handleUpdateBatch"
          v-hasPermi="['kylin:tradeCal:edit']">
          修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDeleteBatch"
          v-hasPermi="['kylin:tradeCal:delete']">
          删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sync" @click="handleSync" v-hasPermi="['kylin:tradeCal:sync']">
          同步Tushare数据
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tradeCalList" @selection-change="handleSelectionChange" style="width: 100%">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日历日期" prop="calDate" width="120" align="center">
        <template v-slot="scope">
          {{ formatDate(scope.row?.calDate) }}
        </template>
      </el-table-column>
      <el-table-column label="交易状态" prop="isOpen" width="100" align="center">
        <template v-slot="scope">
          <el-tag :type="scope.row?.isOpen ? 'success' : 'info'">
            {{ scope.row?.isOpen ? '交易日' : '休市日' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上一个交易日" prop="pretradeDate" width="120" align="center">
        <template v-slot="scope">
          {{ scope.row?.pretradeDate ? formatDate(scope.row.pretradeDate) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['kylin:tradeCal:edit']">修改
          </el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['kylin:tradeCal:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize" :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="日历日期" prop="calDate">
          <el-date-picker v-model="form.calDate" type="date" placeholder="请选择日历日期" value-format="YYYYMMDD"
            style="width: 100%" :disabled="!isAdd" />
        </el-form-item>
        <el-form-item label="交易状态" prop="isOpen">
          <el-radio-group v-model="form.isOpen">
            <el-radio label="1">交易日</el-radio>
            <el-radio label="0">休市日</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="上一个交易日" prop="pretradeDate">
          <el-date-picker v-model="form.pretradeDate" type="date" placeholder="请选择上一个交易日" value-format="YYYYMMDD"
            style="width: 100%" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addFutureTradeCal, delFutureTradeCal, getFutureTradeCalList, syncFutureTradeCal, updateFutureTradeCal } from '@/api/kylin/futureTradeCal';
import RightToolbar from "@/components/RightToolbar";

export default {
  name: 'FutureTradeCal',
  components: {
    RightToolbar
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 期货交易日历表格数据
      tradeCalList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否为添加操作
      isAdd: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        beginDate: '',
        endDate: '',
        isOpen: ''
      },
      // 表单参数
      form: {
        calDate: '',
        isOpen: '1',
        pretradeDate: ''
      },
      // 表单校验
      rules: {
        calDate: [
          { required: true, message: '日历日期不能为空', trigger: 'blur' }
        ],
        isOpen: [
          { required: true, message: '交易状态不能为空', trigger: 'change' }
        ],
        pretradeDate: [
          { message: '请选择上一个交易日', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 获取列表
     */
    getList() {
      this.loading = true
      getFutureTradeCalList(this.queryParams).then(response => {
        this.tradeCalList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /**
     * 格式化日期
     */
    formatDate(dateStr) {
      if (!dateStr || dateStr.length !== 8) {
        return dateStr
      }
      return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`
    },
    /**
     * 搜索按钮点击事件
     */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /**
     * 重置按钮点击事件
     */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /**
     * 分页大小改变
     */
    handleSizeChange(size) {
      this.queryParams.pageSize = size
      this.getList()
    },
    /**
     * 当前页码改变
     */
    handleCurrentChange(current) {
      this.queryParams.pageNum = current
      this.getList()
    },
    /**
     * 多选框选中数据
     */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /**
     * 新增按钮点击事件
     */
    handleAdd() {
      this.isAdd = true
      this.open = true
      this.title = '添加期货交易日历'
      this.resetForm('form')
      // 默认当前日期
      const now = new Date()
      this.form.calDate = now.getFullYear() +
        String(now.getMonth() + 1).padStart(2, '0') +
        String(now.getDate()).padStart(2, '0')
      this.form.isOpen = '1'
    },
    /**
     * 批量修改按钮点击事件
     */
    handleUpdateBatch() {
      if (this.ids.length === 1) {
        const row = this.tradeCalList.find(item => item.id === this.ids[0])
        if (row) {
          this.handleUpdate(row)
        }
      }
    },
    /**
     * 修改按钮点击事件
     */
    handleUpdate(row) {
      this.isAdd = false
      this.open = true
      this.title = '修改期货交易日历'
      this.resetForm('form')

      // 填充表单数据（使用可选链避免访问undefined属性）
      this.form.id = row?.id || ''
      this.form.calDate = row?.calDate || ''
      this.form.isOpen = row?.isOpen !== undefined ? String(row.isOpen) : '0'
      this.form.pretradeDate = row?.pretradeDate || ''
    },
    /**
     * 批量删除按钮点击事件
     */
    handleDeleteBatch() {
      this.handleDelete()
    },
    /**
     * 删除按钮点击事件
     */
    handleDelete(row) {
      // 处理批量删除和单行删除的不同情况
      let deleteIds = [];

      // 如果传入了row参数，检查是否为行数据对象
      if (row && typeof row === 'object' && !Array.isArray(row)) {
        // 单行删除情况
        const id = row.id;
        deleteIds = id instanceof Array ? id : [id];
      } else {
        // 批量删除情况 - 使用已选中的ids
        deleteIds = [...this.ids];
      }

      // 检查是否有选中的数据
      if (deleteIds.length === 0) {
        this.$message.warning("请选择要删除的数据项");
        return;
      }

      this.$confirm("是否确认删除选中的数据项？", "警告", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delFutureTradeCal({ calIds: deleteIds })
      }).then(() => {
        this.getList()
        this.$message.success("删除成功")
      }).catch(() => { })
    },
    /**
     * 同步Tushare数据
     */
    handleSync() {
      this.$confirm('确定要同步Tushare数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        this.loading = true
        return syncFutureTradeCal()
      }).then(response => {
        this.loading = false
        this.$message.success(response.msg)
        this.getList()
      }).catch(() => {
        this.loading = false
      })
    },
    /**
     * 提交表单
     */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          const submitData = {
            ...this.form,
            isOpen: parseInt(this.form.isOpen)
          }
          // 确保calDate字段正确发送到后端
          submitData.cal_date = this.form.calDate
          // 确保pretradeDate以正确的字段名发送到后端
          if (this.form.pretradeDate) {
            submitData.pretrade_date = this.form.pretradeDate
          }
          // 如果没有设置上一个交易日，也要确保字段存在
          if (!submitData.pretrade_date) {
            submitData.pretrade_date = null
          }
          if (this.isAdd) {
            addFutureTradeCal(submitData).then(response => {
              if (response.success) {
                this.open = false
                this.getList()
                this.$message.success('添加成功')
              } else {
                // 显示后端返回的错误信息
                this.$message.warning(response.msg || '添加失败')
              }
            })
          } else {
            updateFutureTradeCal(submitData).then(() => {
              this.open = false
              this.getList()
              this.$message.success('修改成功')
            })
          }
        }
      })
    },
    /**
     * 取消按钮点击事件
     */
    cancel() {
      this.open = false
      this.resetForm('form')
    },
    /**
     * 重置表单
     */
    resetForm(formName) {
      this.$refs[formName]?.resetFields()
    }
  }
}
</script>